package cn.wuyu.baselibrary.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import cn.wuyu.baselibrary.R;
import cn.wuyu.baselibrary.utils.DeviceUtil;
import cn.wuyu.baselibrary.utils.ToastUtil;
import cn.wuyu.baselibrary.widget.LoadingLayout;
import cn.wuyu.baselibrary.widget.LoadingView;
import cn.wuyu.baselibrary.widget.WuYuLoadingDialog;

/**
 * author : xuzongmeng
 * date   : 2019/2/19.
 * desc   : 描述
 */

public abstract class BaseFragment extends Fragment {
	protected static final String TAG = "BaseCommonFragment";
	public Activity mContext;
	private FrameLayout mContainer;
	private LoadingLayout mLoadingLayout;
	private LayoutInflater mInflater;
	private String currentClassName;
	/**
	 * 带文字提示的加载弹窗
	 */
	private WuYuLoadingDialog loadingDialog;

	

	
	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		mContext = (Activity) context;
	}
//	private View mRootView;
//	// 处理fragment的布局
//	@Override
//	public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle
//			savedInstanceState) {
//		/*** 避免重复加载 onCreateView */
//		if (mRootView == null) {
//			currentClassName = this.getClass().getSimpleName();
//			this.mInflater = inflater;
//			View view = View.inflate(mContext, R.layout.fragment_base_layout, null);
//			mContainer = view.findViewById(R.id.fl_base_fragment_container);
//			mLoadingLayout = view.findViewById(R.id.loadinglayout_base_fragment);
//			mContainer.addView(mInflater.inflate(getLayoutID(), container, false));
//			mLoadingLayout.setOnReloadListener(v -> onReLoadData());
//			this.mRootView = view;
//			isInit = true;
//			if (isUseEventBus()) {
//				EventBus.getDefault().register(this);
//			}
//			initView(view);
//			/*初始化的时候去加载数据**/
//		} else {
//			ViewGroup parent = (ViewGroup) mRootView.getParent();
//			if (parent != null) {
//				parent.removeView(mRootView);
//			}
//		}
//		isCanLoadData();
//		return mRootView;
//	}


//	private View mRootView;
//	// 处理fragment的布局
//	@Override
//	public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle
//			savedInstanceState) {
//		if (mRootView == null) {
//			currentClassName = this.getClass().getSimpleName();
//			this.mInflater = inflater;
//			mRootView = inflater.inflate( R.layout.fragment_base_layout, null);
//			mContainer = mRootView.findViewById(R.id.fl_base_fragment_container);
//			mLoadingLayout = mRootView.findViewById(R.id.loadinglayout_base_fragment);
//			mContainer.addView(inflater.inflate(getLayoutID(),container,false));
//			mLoadingLayout.setOnReloadListener(v -> onReLoadData());
//			if (isUseEventBus()) {
//				EventBus.getDefault().register(this);
//			}
//			initView(mRootView);
//
//		}
//		ViewGroup parent = (ViewGroup) mRootView.getParent();
//		if (parent != null) {
//			parent.removeView(mRootView);
//		}
//		return mRootView;
//
//	}
	private View mRootView;
	// 处理fragment的布局
	@Override
	public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle
			savedInstanceState) {
		if (mRootView == null) {
			currentClassName = this.getClass().getSimpleName();
			this.mInflater = inflater;
			mRootView = inflater.inflate( R.layout.fragment_base_layout, null);
			mContainer = mRootView.findViewById(R.id.fl_base_fragment_container);
			mLoadingLayout = mRootView.findViewById(R.id.loadinglayout_base_fragment);
			mContainer.addView(inflater.inflate(getLayoutID(),container,false));
			mLoadingLayout.setOnReloadListener(v -> onReLoadData());
			if (isUseEventBus()) {
				EventBus.getDefault().register(this);
			}
			initView(mRootView);

		}

		return mRootView;

	}

	/**
	 * Fragment 处理懒加载，为了防止 setUserVisibleHint 进入多次导致数据重复加载
	 */
	protected boolean isUIVisible = false;
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if (getUserVisibleHint() && mRootView != null && !isUIVisible) {
			isUIVisible = true;
			lazyLoad();
		}
		initData();
	    initListener();
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		if (isVisibleToUser && isVisible() && mRootView != null && !isUIVisible) {
			isUIVisible = true;
			lazyLoad();
		} else {
			super.setUserVisibleHint(isVisibleToUser);
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		this.mContext = null;
		this.mRootView = null;
		isUIVisible = false;
	}
	/**
	 * 是否使用 EventBus
	 */
	public Boolean isUseEventBus(){
		return false;
	}
	/**
	 * 当视图初始化并且对用户可见的时候去真正的加载数据
	 */
	protected void lazyLoad() {
	
	}
//
//	/**
//	 * 当视图已经对用户不可见并且加载过数据，如果需要在切换到其他页面时停止加载数据，可以调用此方法
//	 */
//	protected void stopLoad() {
//	}

	/**
	 * 添加事件监听
	 */
	protected void initListener() {
	}
	/**
	 * 设置布局ID，子类必须实现滴方法
	 */
	public abstract int getLayoutID();
	
	/**
	 * getLayoutID完成后 初始化View，由子类去实现
	 */
	protected  void initView(View view){

	}
	
	/**
	 * 初始化数据, 可以不实现，如果不想用懒加载滴加载数据 可以重载此方法,
	 * 所有Fragment一次性加载所有数据
	 */
	
	protected void initData() {
	}
	
	
	/**
	 * 重新加载数据   当子类需要时 可以重载此方法
	 */
	public void onReLoadData() {
	
	}
	private void closeLoadingView() {
		if (mLoadingView != null) {
			mLoadingView.stopAnim();
		}
	}
	
	
	/**
	 * 显示加载中 代码形式
	 */
	private LoadingView mLoadingView = null;
	
	public void showLoading() {
		if (DeviceUtil.isConnectNet(mContext)) {
			LoadingView loadingView = new LoadingView(mContext, "正在加载中....");
			loadingView.startAnim();
			mLoadingLayout.setLoadingPage(loadingView.getLoadingView());
			mLoadingLayout.setStatus(LoadingLayout.Loading);
			Log.d(TAG, "基类联网了");
		} else {
			mLoadingLayout.setStatus(LoadingLayout.No_Network);
			Log.d(TAG, "基类没有联网");
		}
	}

    /*=========================================================================================*/
	
	/**
	 * 当项目不满足需时 可传入自己LayoutID，显示不同的内容视图 方便扩展
	 * （根据用户自定义的View或者LayoutID）
	 * 这种方式是让LoadingLayout中滴容器去加载View或者Layout
	 */
	public void showContent(int resId) {
		mContainer.removeViewAt(0);
		mContainer.addView(mInflater.inflate(resId, null));
		closeLoadingView();
		
	}
	
	public void showContent(View view) {
		mContainer.removeViewAt(0);
		mContainer.addView(view);
		closeLoadingView();
	}
	
	/**
	 * 显示内容视图
	 */
	public void showContent() {
		mLoadingLayout.setStatus(LoadingLayout.Success);
		closeLoadingView();
	}
	
	/**
	 * 显示空数据 ，暂时没有数据
	 */
	
	public void showEmpty() {
		mLoadingLayout.setStatus(LoadingLayout.Empty);
		closeLoadingView();
	}
	
	/**
	 * 显示空数据 ，暂时没有数据
	 */
	
	public void showEmpty(String text) {
		mLoadingLayout.setStatus(LoadingLayout.Empty);
		mLoadingLayout.setEmptyText(text);
		closeLoadingView();
	}
	
	/**
	 * 显示空数据 ，暂时没有数据
	 */
	
	public void showEmpty(String hitMsg, int imageRes) {
		mLoadingLayout.setStatus(LoadingLayout.Empty);
		mLoadingLayout.setEmptyText(hitMsg);
		mLoadingLayout.setEmptyImage(imageRes);
		closeLoadingView();
	}
/*=============================错误页面===================================*/
	
	/**
	 * 显示页面错误
	 */
	public void showError() {
		mLoadingLayout.setStatus(LoadingLayout.Error);
		closeLoadingView();
	}
	
	/**
	 * 显示页面错误
	 */
	public void showError(String btnMsg) {
		mLoadingLayout.setStatus(LoadingLayout.Error);
		mLoadingLayout.setReloadButtonText(btnMsg);
		closeLoadingView();
	}
	
	/**
	 * 显示页面错误
	 */
	public void showError(String btnMsg, String hitMsg) {
		mLoadingLayout.setStatus(LoadingLayout.Error);
		mLoadingLayout.setErrorText(hitMsg);
		mLoadingLayout.setReloadButtonText(btnMsg);
		closeLoadingView();
	}
	
	/**
	 * 显示页面错误
	 */
	public void showError(String text, int imageRes) {
		mLoadingLayout.setStatus(LoadingLayout.Error);
		mLoadingLayout.setErrorText(text);
		mLoadingLayout.setErrorImage(imageRes);
		closeLoadingView();
	}
	
	/**
	 * 显示页面错误
	 */
	public void showError(String btnMsg, String hitMsg, int imageRes) {
		mLoadingLayout.setStatus(LoadingLayout.Error);
		mLoadingLayout.setErrorText(hitMsg);
		mLoadingLayout.setReloadButtonText(btnMsg);
		mLoadingLayout.setErrorImage(imageRes);
		closeLoadingView();
		
	}
	
	/**
	 * 显示没有网络的情况
	 */
	public void showNoNetwork() {
		mLoadingLayout.setStatus(LoadingLayout.No_Network);
		closeLoadingView();
	}

/*-------------------------------------分割线-------------------------------------------------*/
	
	protected void makeToast(String text) {
		ToastUtil.show(text);
	}
	
	/**
	 * 显示加载弹窗
	 */
	public void showLoadingDialog(String message) {
		AppCompatActivity activity = (AppCompatActivity) getActivity();
		assert activity != null;
//		android.app.FragmentManager fragmentManager = activity.getFragmentManager();
		if (loadingDialog != null && loadingDialog.getDialog() != null && loadingDialog.getDialog().isShowing()) {
			loadingDialog.dismiss();
			loadingDialog.stopAnim();
			return;
		}
		if (loadingDialog != null && loadingDialog.getDialog() != null && !loadingDialog.getDialog().isShowing()) {
			loadingDialog.setMessage(message);
			loadingDialog.startAnim();
			loadingDialog.show(activity.getSupportFragmentManager(), "loadingDialog");
			return;
		}
		if (loadingDialog == null || loadingDialog.getDialog() == null) {
			loadingDialog = new WuYuLoadingDialog();
			loadingDialog.setMessage(message);
			loadingDialog.startAnim();
			loadingDialog.show(activity.getSupportFragmentManager(), "loadingDialog");
			
		}
	}
	
	/**
	 * 显示加载弹窗
	 */
	public void showLoadingDialog() {
		showLoadingDialog("加载中");
	}
	
	/**
	 * 关闭加载弹窗
	 */
	public void closeLoadingDialog() {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
			loadingDialog.stopAnim();
		}
	}
	
	/**
	 * 是否点击了多次 小于1秒当作是一次点击了
	 **/
	private long curClickTimeMillis = 0;
	
	protected boolean isMultiplicationClick() {
		if (curClickTimeMillis == 0) {
			curClickTimeMillis = System.currentTimeMillis();
			return false;
		}
		boolean rs = System.currentTimeMillis() - curClickTimeMillis < 3000;
		curClickTimeMillis = System.currentTimeMillis();
		return rs;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(currentClassName);
	}
	
	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(currentClassName);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (isUseEventBus()) {
			EventBus.getDefault().unregister(this);
		}
	}
//
//	private void setData(List data, boolean  isFirstLoad, boolean  isRefresh, SwipeRefreshLayout refreshLayout, RecyclerView rvList,BaseQuickAdapter mAdapter) {
//		if (isFirstLoad) {
//			isFirstLoad = false;
//		}
//		showContent();
//		int size = data.size();
//		if (isRefresh) {
//			if (size != 0) {
//				mAdapter.setNewData(data);
//				mAdapter.disableLoadMoreIfNotFullPage(rvList);
//			} else {
//				showEmpty();
//			}
//		} else {
//			if (size != 0) {
//				mAdapter.addData(data);
//				mAdapter.loadMoreComplete();
//			} else {
//				mAdapter.loadMoreEnd();
//			}
//		}
//		finishRefreshOrLoadMore(refreshLayout);
//	}
//
//	private void finishRefreshOrLoadMore(SwipeRefreshLayout refreshLayout) {
//		if (refreshLayout.isRefreshing()) refreshLayout.setRefreshing(false);
//		if (mAdapter.isLoading) mAdapter.loadMoreComplete();
//	}
}
